package com.chixing.dao;

import com.chixing.dao.mapper.RowMapper;
import com.chixing.pojo.Employee;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * 数据增删改查的通用化模板
 */
public class JdbcTemplate<T> {

    private RowMapper<T> rowMapper;

    public JdbcTemplate(RowMapper<T> rowMapper) {
        this.rowMapper = rowMapper;
    }

// 查询单个对象  select
    // 根据主键查询商品  select * from product where pro_id = ?
    // 用户名与密码查询 select user_id,username,user_age,password,email,telno
    //                          from user where username = ? and password = ? and telno = ?


    // T :  User
    public T queryForObject(String sql,Object... args){  //args("smith","abc123",189382992L)
       Connection connection =  DBConn.getConnection();
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        T t = null;
        try {
            pstmt = connection.prepareStatement(sql);
            if(args!=null){ // 防止空指针异常
                for(int i =0;i<args.length;i++){
                    pstmt.setObject(i+1,args[i]);
                }
            }

            rs = pstmt.executeQuery();
                t = rowMapper.mapper(rs);



        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            if(rs !=null) {
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(pstmt !=null) {
                try {
                    pstmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            DBConn.closeConnection();
        }


         return t;
    }

    // 查询返回多个对象 select
    public List<T> queryForList(String sql, Object... args){
        return null;
    }


    // update(修改了数据库里面的数据 )sql : insert ,update ,delete
    public int update(String sql, Object... args){
        Connection connection =  DBConn.getConnection();
        PreparedStatement pstmt = null;

        int rows = 0;
        try {
            pstmt = connection.prepareStatement(sql);
            if(args!=null){ // 防止空指针异常
                for(int i =0;i<args.length;i++){
                    pstmt.setObject(i+1,args[i]);
                }
            }
            rows = pstmt.executeUpdate();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            if(pstmt !=null) {
                try {
                    pstmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            DBConn.closeConnection();
        }


        return rows;
    }


}
